<template>
  <div class="main ad-manage-edit">
    <section>
      <el-form :model="rainForm" ref="rainForm" label-width="150px" :rules="rule">
        <el-form-item label="活动名称：" prop="title">
          <el-input v-model="rainForm.title"></el-input>
        </el-form-item>
        <el-form-item label="开始时间：" prop="startTime">
          <el-date-picker v-model="rainForm.startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="红包总金额：">
          <el-button type="primary" @click="addRow()" size="mini">添加</el-button>
          <div class="row-container">
            <el-row :gutter="20" v-for="(item,index) in rainForm.hongbaoRainRuleList" :key="index">
              <el-col :span="2"><span>规则{{index + 1}}:</span></el-col>
                <el-input :disabled="true" v-model="item.fromPersonNumber" :min="1" type="number" placeholder="">
                  <template slot="append">人</template>
                </el-input>
                <span style="margin: 0 10px"> ~ </span>
                <el-input v-model="item.toPersonNumber" :disabled="index + 1 !== rainForm.hongbaoRainRuleList.length" type="number" :min="1" placeholder="">
                  <template slot="append">人</template>
                </el-input>
              <el-col :span="6">
                <el-input v-model="item.totalAmount" :disabled="index + 1 !== rainForm.hongbaoRainRuleList.length" oninput="if(value.length>13)value=value.slice(0,13)" type="number" :min="1" maxLength="3" placeholder="">
                  <template slot="prepend">总金额</template>
                  <template slot="append">元</template>
                </el-input>
              </el-col>
              <el-col :span="2">
                <el-button @click="removeRow(index)" v-if="index + 1 === rainForm.hongbaoRainRuleList.length" type="text" size="mini" class="el-icon-remove" style="color:red;margin-left:10px;">移除</el-button>
              </el-col>
            </el-row>
          </div>
        </el-form-item>
        <el-form-item label="现金红包使用时间：" prop="timeRange">
          <el-date-picker
            v-model="rainForm.timeRange"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="红包雨活动背景图:" prop="backgroundPic">
          <el-upload
            class="avatar-uploader"
            accept="image/*"
            :action="upladUrl"
            name="file"
            :show-file-list="false"
            :on-success="uploadBGSuccess">
            <img v-if="rainForm.backgroundPic" :src="rainForm.backgroundPic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="活动规则:" prop="activityRule">
          <tinymce :height="300" v-model="rainForm.activityRule"></tinymce>
        </el-form-item>

        <el-form-item label="消息推送主图:" prop="messagePic">
          <el-upload
            class="avatar-uploader"
            accept="image/*"
            :action="upladUrl"
            name="file"
            :show-file-list="false"
            :on-success="uploadSuccess">
            <img v-if="rainForm.messagePic" :src="rainForm.messagePic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="消息推送主标题：" prop="messageTitle">
          <el-input v-model="rainForm.messageTitle"></el-input>
        </el-form-item>

        <el-form-item label="消息推送副标题：" prop="messageSubTitle">
          <el-input v-model="rainForm.messageSubTitle"></el-input>
        </el-form-item>
        <el-form-item label="跳转URL:" prop="useLink" :rules="commonRules.urlRule">
          <el-input v-model="rainForm.useLink" placeholder="http(s)://"></el-input>
        </el-form-item>

        <el-form-item label="是否启动：">
          <el-switch v-model="rainForm.enabled" :active-value="1" :inactive-value="0">
          </el-switch>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="comfirm()">确 定</el-button>
        </el-form-item>

      </el-form>
    </section>
  </div>

</template>

<script>
  import { getPacketRainDetail, packetAction } from '@/api/searchMsg'
  import Tinymce from '@/components/Tinymce'

  export default {
        name: "edit",
      components: {
        Tinymce
      },
      data() {
          return {
            rainForm: {
              title: '',
              startTime: '',
              timeRange: '',
              useStartTime: '',
              useEndtTime: '',
              enabled: 0,
              backgroundPic: '',
              activityRule: '',
              messagePic: '',
              messageTitle: '',
              messageSubTitle: '',
              hongbaoRainRuleList: [{ fromPersonNumber: 1, toPersonNumber: '', totalAmount: '' }]
            },
            rule: {
              title: [
                { required: true, message: '请输入活动名称!', trigger: 'blur' }
              ],
              startTime: [
                { required: true, message: '请选择开始时间!', trigger: 'blur' }
              ],
              timeRange: [
                { required: true, message: '请选择起止时间!', trigger: 'blur' }
              ],
              backgroundPic: [
                { required: true, message: '请选择背景图!', trigger: 'blur' }
              ],
              activityRule: [
                { required: true, message: '请填写活动规则!', trigger: 'blur' }
              ],
              messagePic: [
                { required: true, message: '请选择主图!', trigger: 'blur' }
              ],
              messageTitle: [
                { required: true, message: '请填写主标题!', trigger: 'blur' }
              ],
              messageSubTitle: [
                { required: true, message: '请填写副标题!', trigger: 'blur' }
              ],
              useLink: [
                { required: true, message: '请填写url!', trigger: 'blur' }]
            }
          }
      },
      created(){
          if(this.$route.query.id){
            this.initDetail()
          }
      },
      methods: {

          async uploadBGSuccess(res) {
            this.rainForm.backgroundPic = this.replaceImgUrl(res.filePath);
          },
          async uploadSuccess(res) {
            this.rainForm.messagePic = this.replaceImgUrl(res.filePath);
          },
          async initDetail(){
            const res = await getPacketRainDetail({hongbaoRainActivityId: this.$route.query.id})
            this.rainForm = res.data
            if (res.data.useStartTime){
              this.rainForm.timeRange = [res.data.useStartTime, res.data.useEndTime]
            }
          },

        addRow() {
          let rainForm = this.rainForm.hongbaoRainRuleList;
          if (this.rainForm.hongbaoRainRuleList.length < 1) {
            this.rainForm.hongbaoRainRuleList.push({ fromPersonNumber: 1, toPersonNumber: '', totalAmount: '' })
          }
          if (this.rainForm.hongbaoRainRuleList[this.rainForm.hongbaoRainRuleList.length - 1].toPersonNumber == '' || this.rainForm.hongbaoRainRuleList[this.rainForm.hongbaoRainRuleList.length - 1].totalAmount == '') {
            this.$message({
              type: 'warning',
              message: '请先完成上一个规则！'
            })
            return false;
          } else {
            if (this.rainForm.hongbaoRainRuleList[this.rainForm.hongbaoRainRuleList.length - 1].toPersonNumber <= this.rainForm.hongbaoRainRuleList[this.rainForm.hongbaoRainRuleList.length - 1].fromPersonNumber) {
              this.$message({
                type: 'warning',
                message: '参与人数范围结束值必须大于开始值！'
              })
              return false;
            } else {
              if (rainForm.length >= 2) {
                let parentPrice = parseInt(rainForm[rainForm.length - 2].totalAmount);
                let childPrice = parseInt(rainForm[rainForm.length - 1].totalAmount)
                if (childPrice > parentPrice) {
                  this.rainForm.hongbaoRainRuleList.push({ fromPersonNumber: parseInt(this.rainForm.hongbaoRainRuleList[this.rainForm.hongbaoRainRuleList.length - 1].toPersonNumber) + 1, toPersonNumber: '', totalAmount: '' })
                } else {
                  this.$message({
                    type: 'warning',
                    message: '总金额必须大于上一条规则！'
                  })
                }
              } else {
                this.rainForm.hongbaoRainRuleList.push({ fromPersonNumber: parseInt(this.rainForm.hongbaoRainRuleList[this.rainForm.hongbaoRainRuleList.length - 1].toPersonNumber) + 1, toPersonNumber: '', totalAmount: '' })

              }
            }
          }
        },


        isLastGreater() {
          let last = this.rainForm.hongbaoRainRuleList;
          if (last.length > 1) {

            if (parseInt(last[last.length - 1].totalAmount) <= parseInt(last[last.length - 2].totalAmount)) {
              this.$message({
                type: 'warning',
                message: `每条规则的金额必须大于上一条规则`,
              })
              return false;
            } else {
              return true;
            }
          } else {
            return true;
          }
        },
        comfirm() {
          this.$refs['rainForm'].validate((valid) => {
            if (valid) {
              let last = this.rainForm.hongbaoRainRuleList[this.rainForm.hongbaoRainRuleList.length - 1];
              if (this.rainForm.hongbaoRainRuleList[this.rainForm.hongbaoRainRuleList.length - 1].toPersonNumber !== '' && this.rainForm.hongbaoRainRuleList[this.rainForm.hongbaoRainRuleList.length - 1].totalAmount !== '') {
                let flag = true;
                this.rainForm.hongbaoRainRuleList.map((item, idex) => {
                  if (parseInt(item.toPersonNumber) <= parseInt(item.fromPersonNumber)) {
                    this.$message({
                      type: 'warning',
                      message: `规则 ${idex + 1} 填写不正确，数值范围结束值必须大于初始值`,
                    })
                    flag = false;
                    return false;
                  } else {
                    flag = true;
                  }
                })
                if (flag && this.isLastGreater()) {
                  this.save();
                }
              } else {
                this.$message({
                  type: 'error',
                  message: '请完成规则填写！'
                })
              }

            } else {
              console.log('error submit!!');
              return false;
            }
          });
        },
        async save() {
          let res;
          this.rainForm.useStartTime = this.rainForm.timeRange[0]
          this.rainForm.useEndTime = this.rainForm.timeRange[1]
          if (this.$route.query.id) {
            res = await packetAction(this.rainForm, '', 'put');
          } else {
            res = await packetAction(this.rainForm, '', 'post');
          }
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: res.message
            })
            setTimeout(this.$router.go('-1'), 500)
          }
        },
        removeRow(index) {
          this.rainForm.hongbaoRainRuleList.splice(index, 1)
        }


      }
    }
</script>

<style scoped>
  .el-row { display: flex; margin-bottom: 10px}
    .row-container .el-input,
    .row-container .el-textarea,
    .row-container .el-select,
    .row-container .el-date-editor {
      width: auto !important;
    }
    .row-container {
      margin: 20px 0;
    }

</style>
